package com.toprs.business.service

import com.alibaba.fastjson2.JSONObject
import com.toprs.base.config.RequestHolder
import com.toprs.base.entity.User
import com.toprs.base.exception.CustomException
import com.toprs.base.mapper.UserMapper
import com.toprs.base.mapper.select
import com.toprs.base.mapper.UserDynamicSqlSupport
import com.toprs.business.entity.Step
import com.toprs.business.mapper.ApplicationBaseMapper
import com.toprs.business.mapper.StepMapper
import com.toprs.business.mapper.selectByAppId
import com.toprs.business.mapper.selectByPrimaryKey
import org.springframework.stereotype.Service


@Service
class StepService(val stepMapper: StepMapper, val appMapper: ApplicationBaseMapper, val userMapper: UserMapper) {

    fun getStepList(id: Int): List<Step> {

        val list = stepMapper.selectByAppId(id)

        return list
    }

    fun getBackUserList(id: Int): List<JSONObject> {

        val app = appMapper.selectByPrimaryKey(id) ?: throw CustomException("申请不存在！")


        var userIds = mutableListOf<String>()

        if (app.stateId == 2.toShort()) {
            userIds.add(app.applicant!!)
        } else if (app.stateId == 3.toShort()) {
            val opeartor = RequestHolder.getUserId()
            userIds = (getStepList(id).filter { it.operatorId != opeartor }.map { it.operatorId!! }).toMutableList()
        }

        return userMapper.select {
            where {
                UserDynamicSqlSupport.userid.isIn(userIds)
            }
        }.map { JSONObject.parseObject("{\"userid\":\"${it.userid}\",\"realname\": \"${it.realname}\",}") }
    }
}